package com.smart.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.smart.model.Admin;

public class LoginCheckFilter implements Filter{
	 private FilterConfig config=null;
	 private String Webroot=null;
	 private List<String> rules=null; 
	 public void init(FilterConfig filterConfig) throws ServletException {
	 this.config=filterConfig;
	 System.out.println("hello logincheckFilter init method");
	 Webroot=config.getServletContext().getContextPath();
	 rules=new ArrayList<String>();
	 rules.add(Webroot+"/css/.*");
	 rules.add(Webroot+"/js/.*");
	 rules.add(Webroot+"/images/.*");
	 rules.add(Webroot+"/fonts/.*");
	 rules.add(Webroot+"/ueditor/.*");
	 rules.add(Webroot+"/views/wechat/.*");
	 }
	 public void destroy() {
	  System.out.println("登录检查过滤器销毁");
	 }
	 
	 //判断是否可以通过 
	 public boolean canPass(String uri)
	 {
		 boolean res=false;
		 //放过去pc的登录页面和登录数据请求
		 if(uri.equals(Webroot+"/views/pc/login.html")||uri.equals(Webroot+"/login_check"))
		 {
			 res=true;
		 }
		 else//放过去一些静态资源，准备采用正则表达式
		{
			 for(String str:rules)
			 {
				if(Pattern.matches(str,uri)) {res=true;break;}
			 }
		}
		 return res;
	 }
	public void doFilter(ServletRequest request, ServletResponse response,
	  FilterChain chain) throws IOException, ServletException {
	 HttpServletRequest req=(HttpServletRequest)request;
	 HttpServletResponse resp=(HttpServletResponse)response;
	 HttpSession session=req.getSession(false);
//	 System.out.println("Webroot:"+Webroot);
	 String uri=req.getRequestURI();

	 System.out.println("request uri:"+uri);
	 //对登录页面和登录处理Servlet、错误页面直接放过
	 if(uri!=null&&canPass(uri))
	 {
	   System.out.println("uri:"+uri+"放过去");
	   chain.doFilter(req,resp);
	 }    
	 else
	 {
	    //检查session和session中账号是否存在，选择阻断或通过
	    if(session==null)
	    {
	    	     System.out.println("session null,"+uri+"阻止访问");
	             resp.sendRedirect("/SmartCommunity/views/pc/login.html");
	    }
	    else
	    {
	         Admin admin=(Admin)session.getAttribute("admin");
	         if(admin==null)
	         {
	        	 System.out.println("admin null,"+uri+"阻止访问");
	            resp.sendRedirect("/SmartCommunity/views/pc/login.html");
	         }
	         else
	         {
	        	System.out.println("admin exist,"+uri+"放过去");
	            chain.doFilter(req,resp);
	         }
	    }
	  }
	 }   
}
